package com.controller.system;


import com.common.PageResultUtil;
import com.common.ResultUtil;
import com.common.WebContextHelper;
import com.common.stereotype.Module;
import com.common.stereotype.Token;
import com.common.stereotype.Uri;
import com.controller.base.BaseLocalController;
import com.entity.Manager;
import com.entity.Role;
import com.entity.dictionary.Department;
import com.facade.dictionary.dept.IDepartmentFacadeR;
import com.facade.role.IRoleFacadeR;
import com.facade.user.cud.IManagerFacadeCUD;
import com.facade.user.r.IManagerFacadeR;
import com.query.ManagerQueryLink;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/manager")
@Module(parent = "系统模块", name = "用户管理", parentModuleOrder = 0, childModuleOrder = 3)
public class ManagerController extends BaseLocalController {

    @Resource
    private IManagerFacadeR managerFacadeR;
    @Resource
    private IManagerFacadeCUD managerFacadeCUD;
    @Resource
    private IRoleFacadeR roleFacadeR;
    @Resource
    private IDepartmentFacadeR departmentFacadeR;

    private static final String managerDefaultPassword = "123456";

    @ModelAttribute
    public void prepare(Long id, ModelMap modelMap) {
        HttpServletRequest request = WebContextHelper.getRequest();
        String requestUri = request.getRequestURI();
        if (requestUri.contains("modify") && null != id) {
            modelMap.addAttribute(managerFacadeR.findByPrimaryKey(id));
        }
    }

    @RequestMapping(value = "/query.htm")
    @Uri(name = "查询", uri = "/manager/query", order = 0)
    public String query(@ModelAttribute("query") ManagerQueryLink query, ModelMap modelMap) {
        PageResultUtil<Manager> paging = managerFacadeR.queryManagerPageLink(query);
        for (Manager manager : paging.getItems()) {
            Long departmentId = manager.getDepartmentId();
            manager.setDepartments(departmentFacadeR.findFullPropertyText(departmentId, "pid", "name", " - ", true));
        }
        modelMap.addAttribute("paging", paging);
        return "system/manager-List";
    }

    @RequestMapping(value = "/edit.htm")
    public String edit(Long id, ModelMap modelMap) {
        List<Role> roleList = roleFacadeR.findAll("seq ASC");
        if (null != id) {
            Manager manager = managerFacadeR.findByPrimaryKey(id);
            if (null != manager) {
                modelMap.addAttribute("manager", manager);
                List<Role> userRoleList = roleFacadeR.findByUserLink(id);
                List<Long> userRoleIdList = new ArrayList<>();
                for (Role role : userRoleList) {
                    userRoleIdList.add(role.getId());
                }
                for (Role role : roleList) {
                    if (userRoleIdList.contains(role.getId())) {
                        role.setChecked(true);
                    }
                }
            }
            Long departmentLv1Id = null;
            Long departmentLv2Id = null;
            Long departmentId = manager.getDepartmentId();
            if (null != departmentId) {
                Department department = departmentFacadeR.findByPrimaryKey(departmentId);
                if (null != department) {
                    Long departmentPid = department.getPid();
                    if (null != departmentPid) {
                        departmentLv1Id = departmentPid;
                        departmentLv2Id = departmentId;
                    } else {
                        departmentLv1Id = departmentId;
                    }
                }
            }
            if (null != departmentLv1Id) {
                modelMap.addAttribute("departmentLv2List", departmentFacadeR.findByPropertyEqualTo("pid", departmentLv1Id, "seq ASC"));
            }
            modelMap.addAttribute("departmentLv1Id", departmentLv1Id);
            modelMap.addAttribute("departmentLv2Id", departmentLv2Id);
        }
        modelMap.addAttribute("roleList", roleList);
        modelMap.addAttribute("departmentLv1List", departmentFacadeR.findByPropertyEqualTo("pid", null, "seq ASC"));
        return "system/manager-edit";
    }

    @Token
    @ResponseBody
    @RequestMapping(value = "/add.htm")
    @Uri(name = "添加", uri = "/manager/add", order = 1)
    public ResultUtil add(@Valid Manager manager, BindingResult error, Long[] roleId) {
        ResultUtil resultUtil = validate(error);
        if (ResultUtil.SUCCESS != resultUtil.getStatus()) {
            return resultUtil;
        }
        manager.setStatus(9);
        manager.setPassword(managerDefaultPassword);
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.addManager(manager, roleId, onLineUser.getId());
    }

    @Token
    @ResponseBody
    @RequestMapping(value = "/modify.htm")
    @Uri(name = "修改", uri = "/manager/modify", order = 2)
    public ResultUtil modify(@Valid Manager manager, BindingResult error, Long[] roleId) {
        ResultUtil resultUtil = validate(error);
        if (ResultUtil.SUCCESS != resultUtil.getStatus()) {
            return resultUtil;
        }
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.modifyManager(manager, roleId, onLineUser.getId());
    }

    @ResponseBody
    @RequestMapping(value = "/resetPassword.htm/{id}")
    @Uri(name = "密码重置", uri = "/manager/resetPassword", order = 3)
    public ResultUtil resetPassword(@PathVariable("id") Long id) {
        return managerFacadeCUD.modifyPassword(id, managerDefaultPassword);
    }

    @ResponseBody
    @RequestMapping(value = "/delete.htm/{id}")
    @Uri(name = "删除", uri = "/manager/delete", order = 4)
    public ResultUtil delete(@PathVariable("id") Long id) {
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.deleteManager(id, onLineUser.getId());
    }

    @ResponseBody
    @RequestMapping(value = "/enable.htm/{id}")
    @Uri(name = "解锁", uri = "/manager/enable", order = 5)
    public ResultUtil enable(@PathVariable("id") Long id) {
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.enableManager(id, onLineUser.getId());
    }

    @ResponseBody
    @RequestMapping(value = "/disable.htm/{id}")
    @Uri(name = "锁定", uri = "/manager/disable", order = 6)
    public ResultUtil disable(@PathVariable("id") Long id) {
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.disableManager(id, onLineUser.getId());
    }

    @RequestMapping(value = "/editPassword.htm")
    public String editPassword() {
        return "system/manager-modify-password";
    }

    @Token
    @ResponseBody
    @RequestMapping(value = "/modifyPassword.htm")
    public ResultUtil modifyPassword(@RequestParam("newPassword") String newPassword) {
        Manager onLineUser = WebContextHelper.getOnLineUser();
        return managerFacadeCUD.modifyPassword(onLineUser.getId(), newPassword);
    }
}